//填充每个节点的下一个右侧节点指针 II
//https://leetcode.cn/problems/populating-next-right-pointers-in-each-node-ii/description/
/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* left;
    Node* right;
    Node* next;

    Node() : val(0), left(NULL), right(NULL), next(NULL) {}

    Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}

    Node(int _val, Node* _left, Node* _right, Node* _next)
        : val(_val), left(_left), right(_right), next(_next) {}
};
*/

class Solution {
public:
    Node* connect(Node* root) 
    {
        if(root == nullptr) return nullptr;
        //层序遍历
        queue<Node*> q;
        q.push(root);
        Node* prev = nullptr;
        while(!q.empty())
        {
            int n = q.size();
            for(int i = 0; i < n; i++)
            {
                Node* cur = q.front(); q.pop();
                if(cur->left) q.push(cur->left);
                if(cur->right) q.push(cur->right);                
                if(prev != nullptr) prev->next = cur;
                prev = cur;
            }
            prev = nullptr;
        }
        return root;
    }
};